<template>
  <div class="map">
    <div class="map1"><img src="@/assets/images/overView/map-bg.png" /></div>
    <div id="map_1" class="map2" @dblclick="mapBack" />
  </div>
</template>

<script lang="ts" setup>
import ChinaJSON from '@/assets/map/china.json'; // 中国地图
import { provincesMap, cityMap } from '@/assets/city/map';
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { largeScreeStationList } from '@/service/apis/statistical';

const mapList = ref([] as any[]);
const historyMap = ref({} as any);
const provinceMap = ref();
const provinceCode = ref('');
let myChart: any = null;
const timer = ref();
const mapName = ref('china');
const cityCode = ref();

// 大屏电站列表
const getLargeScreeStationList = () => {
  // console.log(provinceCode.value);

  largeScreeStationList({
    provinceCode: provinceCode.value,
  })
    .then((res: any) => {
      if (historyMap.value.type === 2) {
        const arr: any[] = [];
        res?.largeScreeStationDTOList.forEach((item: any) => {
          if (item.cityCode === cityCode.value) {
            arr.push(item);
          }
        });
        mapList.value = arr;
      } else {
        mapList.value = res?.largeScreeStationDTOList || [];
      }
      initEcharts(mapName.value, mapList.value);
      clearInterval(timer.value);
      timer.value = null;
      startInterval();
    })
    .catch(() => {});
};

const startInterval = () => {
  timer.value = setInterval(() => {
    getLargeScreeStationList();
  }, 1000 * 60 * 5);
};

const leftSlideData: any = ref({});
const leftslide = () => {
  let url = window.location.origin + '/overViewStation?id=' + leftSlideData.value.id
  window.open(url, '_blank');
}
(window as any).leftslide = leftslide;

const initEcharts = (map: any, list?: any) => {
  const option = {
    tooltip: {
      trigger: 'item',
      padding: 0,
      backgroundColor: 'rgba(0,0,0,0)',
      borderWidth: 0,
      className: 'echarts-tooltip',
      enterable: true,
    },
    geo: {
      map: map,
      left: 'center',
      top: 'middle',
      emphasis: {
        label: {
          show: true,
        },
        itemStyle: {
          areaColor: 'rgba(102,241,250,0.8)',
        },
      },
      roam: true,
      itemStyle: {
        areaColor: 'rgba(63,149,250,0.8)',
        color: 'rgba(0,0,0,0.7)',
      },
      tooltip: {
        show: false,
        formatter: (params: any) => {},
      },
      layoutCenter: ['50%', '50%'],
      // layoutSize: 100,
      scaleLimit: {
        min: 1.2,
        //   max: 3
      },
      zoom: 1.2, // 缩放
      // zoom: 7.1,
    },
    series: [
      {
        name: '',
        type: 'effectScatter',
        // type: list ? 'effectScatter' : 'map',
        geoIndex: 0,
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
        },
        tooltip: {
          show: true,
          formatter: (params: any) => {
            // console.log('series', params);
            const toolData = params?.data || {};
            leftSlideData.value = toolData;

            const toolTiphtml = `
                  <div class='tip' onclick="leftslide()">
                    <div class='tip-title' style='font-size:13px'>${toolData.stationName}</div>
                    <div class='tip-adr'>位置：${toolData.address}</div>
                    <div class='tip-alt'>直流枪数量：${toolData.countFreeConnectorDC}/${toolData.countConnectorDC}</div>
                    <div class='tip-dir'>交流枪数量：${toolData.countFreeConnectorAC}/${toolData.countConnectorAC}</div>
                  </div>
                `;
            return toolTiphtml;
          },
        },
        coordinateSystem: 'geo',
        data: convertData(list),
        symbolSize: function (val: any) {
          const v1 = val[3] ? Number(val[3]) : 0;
          const v2 = val[4] ? Number(val[4]) : 0;
          if (v1 + v2 > 20) {
            return 20;
          } else {
            return v1 + v2;
          }
        },
        label: {
          formatter: '{b}',
          position: 'center',
          show: false,
        },
        emphasis: {
          label: {
            show: false,
          },
        },
        itemStyle: {
          color: '#F3CC26',
        },
        clip: true,
      },
    ],
  };
  myChart.setOption(option, true);
};
// 展示对应的省
const showProvince = (eName: string, param: any) => {
  console.log(eName, param);
  axios.get(`./map/province/${eName}.json`).then((res: any) => {
    const { data } = res;
    console.log('展示对应的省,data', data);
    provinceMap.value = data;
    const obj = ChinaJSON.features.find(
      (item: any) => item.properties.name === param
    );
    if (obj) {
      provinceCode.value = obj.id;
      echarts.registerMap(param, data);
      mapName.value = param;
      getLargeScreeStationList();
    }
  });
};

// 展示对应市
const showCitys = (cName: string, param: any) => {
  console.log(cName, param);
  // 显示县级地图
  axios.get(`./map/city/${cName}.json`).then((res: any) => {
    const { data } = res;
    const obj = provinceMap.value.features.find(
      (item: any) => item.properties.name === param
    );
    if (obj) {
      const arr: any[] = [];
      mapList.value.forEach((item: any) => {
        if (item.cityCode === obj.id) {
          arr.push(item);
        }
      });
      cityCode.value = obj.id;
      mapName.value = param;
      console.log('arr---', arr);
      echarts.registerMap(param, data);
      initEcharts(param, arr);
    }
  });
};

const convertData = (data: any) => {
  if (!data) {
    return [];
  }
  const res: any[] = [];
  data.forEach((item: any, index: number) => {
    if (item.stationLat && item.stationLng) {
      res.push({
        ...item,
        name: item.stationName || '—',
        address: item.address || '—',
        countFreeConnectorAC: item.countFreeConnectorAC || 0,
        countConnectorAC: item.countConnectorAC || 0,
        countFreeConnectorDC: item.countFreeConnectorDC || 0,
        countConnectorDC: item.countConnectorDC || 0,
        value: [
          item.stationLng,
          item.stationLat,
          index,
          item.countConnectorAC,
          item.countConnectorDC,
        ],
      });
    }
  });
  // console.log('res---', res);
  return res;
};

const initMap = (str?: string) => {
  // 基于准备好的dom，初始化echarts实例
  if (str) {
    showProvince(provincesMap[str], str);
  } else {
    echarts.registerMap(mapName.value, ChinaJSON as any);
    getLargeScreeStationList();
  }
  myChart.off('dblclick');
  myChart.on('dblclick', (param: any) => {
    console.log('dblclick,', param);
    if (param.name in provincesMap) {
      // 处理省模块
      const names = param.name;
      for (const key in provincesMap) {
        if (names === key) {
          historyMap.value = {
            type: 1,
            key: key,
          };
          // console.log('ley', key);
          showProvince(provincesMap[key], key);
          break;
        }
      }
    } else if (param.name in cityMap) {
      console.log(param.name, cityMap);
      // 处理市模块
      const names = param.name;
      for (const key in cityMap) {
        if (names === key) {
          historyMap.value.type = 2;
          showCitys(cityMap[key], key);
          break;
        }
      }
    }
    param.event?.stop();
  });
};

const mapBack = () => {
  if (historyMap.value.type === 1) {
    mapName.value = 'china';
    provinceCode.value = '';
    initMap();
    historyMap.value = {};
  } else if (historyMap.value.type === 2) {
    mapName.value = provincesMap[historyMap.value.key];
    initMap(historyMap.value.key);
    historyMap.value.type = 1;
  }
};

onMounted(() => {
  const chartDom = document.getElementById('map_1');
  myChart = echarts.init(chartDom as HTMLElement, {}, { renderer: 'svg' });
  initMap();
});
onUnmounted(() => {
  clearInterval(timer.value);
  timer.value = null;
});
</script>

<style lang="scss" scoped>
.map {
  position: relative;
  height: 100%;
  z-index: 1;
  width: 100%;
}
.map2 {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 999;
}

.map1 {
  // width: 674px;
  width: 743px;
  height: 960px;
  z-index: -1;
  top: -240px;
  // left: -31px;
  left: -90px;
  // animation: myfirst2 15s infinite linear;
  transform-origin: center 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
.map1 {
  position: absolute;
}
::v-deep(.echarts-tooltip) {
  .tip {
    width: 200px;
    background-color: rgba(0, 0, 0, 0.7);
    border-radius: 5px;
    padding: 5px;
    color: #fff;
    cursor: pointer;
    &-title {
      padding: 2px 5px;
      white-space: pre-wrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2; // 控制多行的行数
      -webkit-box-orient: vertical;
      font-size: 10px !important;
    }
    &-adr {
      padding: 0 5px;
      font-size: 8px;
      white-space: pre-wrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2; // 控制多行的行数
      -webkit-box-orient: vertical;
    }
    &-alt {
      color: #2eefdb;
      padding: 0 5px;
      font-size: 8px;
    }
    &-dir {
      color: #2eefdb;
      padding: 0 5px;
      font-size: 8px;
    }
  }
}
</style>